<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级id" prop="claId">
        <el-input
          v-model="queryParams.claId"
          placeholder="请输入班级id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="校区名称" prop="campusName">
        <el-input
          v-model="queryParams.campusName"
          placeholder="请输入校区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班主任" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入班主任名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年级" prop="claGrade">
        <el-input
          v-model="queryParams.claGrade"
          placeholder="请输入年级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="claClass">
        <el-input
          v-model="queryParams.claClass"
          placeholder="请输入班级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="教室名称" prop="claRoom">
        <el-input
          v-model="queryParams.claRoom"
          placeholder="请输入教室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:courseCla:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:courseCla:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:courseCla:remove']"
        >删除</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:courseCla:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseClaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="班级id" align="center" prop="claId" width="60"/>
      <el-table-column label="校区名称" align="center" prop="campusName" width="85" />
      <el-table-column label="班主任名称" align="center" prop="nickName"  width="85"/>
      <el-table-column label="课程名称" align="center" prop="courseName" width="85" />
      <el-table-column label="年级" align="center" prop="claGrade"  width="85"/>
      <el-table-column label="班级" align="center" prop="claClass"  width="60"/>
      <el-table-column label="教室名称" align="center" prop="claRoom"  width="85"/>
      <el-table-column label="班级状态" align="center" prop="claStatus"  width="70">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.art_class_status" :value="scope.row.claStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center" prop="claDescribe"  width="140"/>
      <el-table-column label="开班时间" align="center" prop="startTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计毕业时间" align="center" prop="endTime" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已上课时数" align="center" prop="passNum"   width="85"/>
      <el-table-column label="总课时" align="center" prop="totalNum"   width="70"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:courseCla:edit']"
          >修改</el-button>
          <!-- <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:courseCla:remove']"
          >删除</el-button> -->
          <!-- <el-button
          size="small"
          type="text"
          icon="el-icon-date"
          :disabled="scope.row.claStatus !== 0"
          @click="handleClaSchedule(scope.row)"
          v-hasPermi="['course:courseCla:edit']"
          >
            班级调课
          </el-button> -->
          <!-- 添加学生 -->
          <el-button
          size="small"
          type="text"
          icon="el-icon-plus"
          @click="handleAddStudent(scope.row)"
          v-hasPermi="['course:courseCla:edit']"
          >
            添加学生
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="校区名字" prop="campusName">
              <el-select v-model="form.campusId" placeholder="请选择校区名称" @change="getListTeacherInfo(form.campusId)" :disabled="isCampusSelectDisabled">
                <el-option
                  v-for="campus in campusInfoList"
                  :key="campus.campusId"
                  :label="campus.campusName"
                  :value="campus.campusId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班主任" prop="nickName">
              <el-select v-model="form.userId" placeholder="请选择班主任名称">
                <el-option
                  v-for="teacher in teacherInfoList"
                  :key="teacher.userId"
                  :label="teacher.nickName"
                  :value="teacher.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程名称" prop="courseName">
              <el-select v-model="form.courseId" placeholder="请选择课程名称">
                <el-option
                  v-for="course in courseInfoList"
                  :key="course.courseId"
                  :label="course.courseName"
                  :value="course.courseId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年级" prop="claGrade">
              <el-input v-model="form.claGrade" placeholder="请输入年级" />
            </el-form-item>
            <el-form-item label="班级" prop="claClass">
              <el-input v-model="form.claClass" placeholder="请输入班级" />
            </el-form-item>
            <el-form-item label="教室名称" prop="claRoom">
              <el-input v-model="form.claRoom" placeholder="请输入教室名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级名称" prop="claDescribe">
              <el-input v-model="form.claDescribe" placeholder="请输入班级名称" />
            </el-form-item>
             <el-form-item label="总课时" prop="totalNum">
              <el-input v-model="form.totalNum" placeholder="请输入总课时" />
            </el-form-item>
            <el-form-item label="班级状态" prop="claStatus">
              <el-select v-model="form.claStatus" placeholder="请选择班级状态">
                <el-option
                  v-for="dict in dict.type.art_class_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开班时间" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开班时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预计毕业时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预计毕业时间">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加学生弹框 -->
    <el-dialog
      title="添加学生"
      :visible.sync="dialogVisible"
      width="85%"
    >
     <div style="display: flex; justify-content: center; align-items: center; padding: 20px; min-width: 800px;">
        <el-transfer
          style="width: 100%; max-width: 900px;"
          v-model="value4"
          filterable
          :titles="['全部学生', '该班学生']"
          :button-texts="['移除', '添加']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          @change="handleChange"
          :data="generateData">
          <span slot-scope="{ option }">{{ option.label }}</span>
          <el-button class="transfer-footer" slot="left-footer" size="small">操作</el-button>
          <el-button class="transfer-footer" slot="right-footer" size="small">操作</el-button>
        </el-transfer>
        <el-button type="primary" @click="submitStutentForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourseCla, delBatchCourseStu, addBatchCourseStu, delCourseCla, addCourseCla, updateCourseCla, listLessonInfo, listClassInfo } from "@/api/course/courseCla"
import { listCampusInfo } from "@/api/campus/campusInfo"
import { listUser } from "@/api/course/courseTeacher"
import Cookies from 'js-cookie'
import {listCourseStu, listCourseStuByClaId } from "@/api/course/courseStu"
export default {
  name: "CourseCla",
  dicts: ['art_class_status'],
  data() {
    return {
      generateData:[],
      value4: [],
      // renderFunc(h, option) {
      //   return <span>{ option.stuId } - { option.stuName }</span>;
      // },
      // 当前操作的班级信息
      currentClass: null,
      // 新增学生弹出层
      dialogVisible: false,
      // 新增学生表单
      form: {
        name: "",
        gender: 1,
        age: 0,
      },
      // 新增学生表单校验规则
      rules: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ]
      },
      // 判断是否禁用校区选择
      isCampusSelectDisabled: false,
      // 课程列表
      courseInfoList: [],
      // 教师列表
      teacherInfoList: [],
      // 校区列表
      campusInfoList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级管理表格数据
      courseClaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        claId: null,
        campusId: null,
        nickName: null,
        campusName: null,
        courseId: null,
        lessonId: null,
        claGrade: null,
        claClass: null,
        claRoom: null,
        claStatus: null,
        claDescribe: null,
        startTime: null,
        endTime: null,
        passNum: null,
        totalNum: null,
        empty1: null,
        empty2: null,
        empty3: null,

      },
      // 表单参数
      form: {
        claId: null,
        campusId: null,
        nickName: null,
        lessonId: null,
        courseId: null,
        courseName: null,
        claGrade: null,
        claClass: null,
        claRoom: null,
        claStatus: 0,
        claDescribe: null,
        startTime: null,
        endTime: null,
        passNum: null,
        totalNum: null,
        empty1: null,
        empty2: null,
        empty3: null,
        // 新增时必填
        userId: [
          { required: true, message: "班主任不能为空", trigger: "blur" }
        ],
      },
      // 表单对比参数
      campusIdNew: null,
      // 表单校验
      rules: {
        campusId: [
          { required: true, message: "校区不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    // 查询校区列表
    this.getListCampusInfo()
    //查询教师列表
    // this.getListTeacherInfo()
    //查询课表
    // this.getListLessonInfo()
  },
  methods: {
    cancel(){
      this.dialogVisible = false
    },
    // 提交表单
    submitStutentForm() {
      // 获取当前班级所有学生（右侧面板中的学生）
      console.log("当前班级ID:", this.currentClass?.claId);
      console.log("该班所有学生ID:", this.value4);
      
      // 根据学生ID获取完整的学生信息
      const classStudents = this.generateData.filter(student => 
        this.value4.includes(student.key)
      );
      
      console.log("该班所有学生完整信息:", classStudents);
      console.log("所有可选学生数据:", this.generateData);
      
      // 如果需要调用API保存学生班级关系
      if (this.currentClass && this.value4.length > 0) {
        // 调试信息
        // console.log('当前班级信息:', this.currentClass);
        // console.log('班级ID:', this.currentClass.claId);
        // console.log('班级ID类型:', typeof this.currentClass.claId);
        
        // 这里可以调用API保存学生和班级的关系
        //删除班级学生
        const claId1 = Number(this.currentClass.claId);
        delBatchCourseStu(claId1).then(res => {
          // console.log('删除班级学生成功:', res)
          //添加班级学生
          const stuClaList = this.value4.map(stuId => ({
            claId: this.currentClass.claId,
            stuId: stuId
          }));
          
          // console.log('准备添加的学生数据:', stuClaList);
          
          addBatchCourseStu(stuClaList).then(res => {
            // console.log('添加班级学生成功:', res)
            // console.log(`班级${this.currentClass.claId}的学生列表已更新`);
            this.$message.success('学生信息保存成功');
          }).catch(error => {
            // console.error('添加学生失败:', error)
            this.$message.error('添加学生失败，请重试');
          })
        }).catch(error => {
          // console.log('添加班级学生失败:', error)
          // console.error('删除学生失败:', error)
          this.$message.error('删除学生失败，请重试');
        })
      } else {
        this.$message.warning('没有学生信息需要保存');
      }
      
      // 关闭弹出层
      this.dialogVisible = false;
    },
    handleChange(value, direction, movedKeys) {
      // 获取当前班级ID
      const claId = this.currentClass ? this.currentClass.claId : null;
      // console.log('当前班级ID:', claId);
      
      if (!claId) {
        this.$message.error('未找到班级信息');
        return;
      }
      
      // 根据操作方向处理学生添加或移除
      if (direction === 'right') {
        // 添加学生到班级
        // console.log('添加学生到班级:', movedKeys, '班级ID:', claId);
        // 这里可以调用API添加学生到班级
      } else if (direction === 'left') {
        // 从班级移除学生
        // console.log('从班级移除学生:', movedKeys, '班级ID:', claId);
        // 这里可以调用API从班级移除学生
      }
    },
    //查询教师列表
    getListTeacherInfo(campusId){
       if (campusId) {
        listUser({ campusId }).then(res => {
          this.teacherInfoList = res.rows

          if(campusId != this.campusIdNew || this.campusIdNew == null){
            // 保存当前校区 ID
            const currentCampusId = this.form.campusId;
            // 表单重置，保留校区 ID
            this.reset()
            this.form.campusId = currentCampusId

          }

      // 保存当前选择的校区 ID
      this.campusIdNew = campusId
    })
      } else {
        // 若未选择校区，清空教师列表
        this.teacherInfoList = []
      }
      //选择课表
      this.getListLessonInfo(campusId)
    },
    //选择课表
    getListLessonInfo(campusId){
      listLessonInfo({ campusId }).then(res => {
        this.courseInfoList = res.rows
      })
    },
    handleAddStudent(row){
      // 保存当前操作的班级信息
      this.currentClass = row;
      
      this.dialogVisible = true
      
      // 先获取所有学生数据（左侧面板）
      listCourseStu({ campusId: row.campusId}).then(res => {
        // 转换数据格式以符合穿梭框要求
        this.generateData = res.rows.map(student => ({
          key: student.stuId, // 使用学生ID作为key
          label: `${student.stuName} - ${student.stuId}`, // 显示学生姓名和ID
          disabled: false, // 可以根据需要设置是否禁用
          // 保留原始数据
          stuId: student.stuId,
          claId: this.currentClass.claId,
          stuName: student.stuName,
          ...student
        }))
      }).catch(error => {
        console.error('获取学生数据失败:', error)
        this.$message.error('获取学生数据失败')
        this.generateData = []
      })
      
      // 再获取该班已有学生（右侧面板）
      listCourseStuByClaId(row).then(res => {
        // value4应该是已选中学生的ID数组，不是对象数组
        this.value4 = res.rows.map(student => student.stuId)
      }).catch(error => {
        console.error('获取班级学生数据失败:', error)
        this.$message.error('获取班级学生数据失败')
        this.value4 = []
      })
    },
    handleClaSchedule(row){

       // 检查 row 是否存在
    if (row && row.claId !== null && row.claStatus !== null) {
      alert(row.claId + " " + row.claStatus)
    } else {
      this.$message.warning('数据不完整，无法执行操作')
    }

    },
    /** 查询班级管理列表 */
    getList() {
      this.loading = true
      //查询cookie
      const userCookie = Cookies.get("user");
      if (userCookie) {
        try {
          const user = JSON.parse(userCookie);
          const campusId1 = Number(user.campusId);
          if (campusId1) {
            this.queryParams.campusId = campusId1
          }
        } catch (error) {
          console.error("解析用户信息失败:", error);
        }
      }
      listCourseCla(this.queryParams).then(response => {
        this.courseClaList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        claId: null,
        campusId: null,
        userId: null,
        lessonId: null,
        claGrade: null,
        claClass: null,
        claRoom: null,
        claStatus: 0,
        claDescribe: null,
        startTime: null,
        endTime: null,
        passNum: null,
        claCretime: null,
        claUpdtime: null,
        empty1: null,
        empty2: null,
        empty3: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.claId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      const userCookie = Cookies.get("user");
      if (userCookie) {
        try {
          const user = JSON.parse(userCookie);
          const campusId = Number(user.campusId);
          if (campusId) {
            this.isCampusSelectDisabled = true;
            this.campusInfoList = [];
            listCampusInfo().then(res => {
              this.campusInfoList = res.rows.filter(item => Number(item.campusId) === campusId);
              this.form.campusId = campusId;
              //查询教师列表
              this.getListTeacherInfo(campusId)
              //选择课表
              this.getListLessonInfo(campusId)

            });
          } else {
            this.isCampusSelectDisabled = false;
            this.getListCampusInfo();
            this.form.campusId = null;
          }
        } catch (error) {
          this.isCampusSelectDisabled = false;
          this.getListCampusInfo();
          this.form.campusId = null;
        }
      } else {
        this.isCampusSelectDisabled = false;
        this.getListCampusInfo();
        this.form.campusId = null;
      }
      this.form.claStatus = 0;
      this.open = true;
      this.title = "添加班级管理";
    },
    getListCampusInfo(){
      listCampusInfo().then(res => {
        this.campusInfoList = res.rows
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 禁用校区选择
      this.isCampusSelectDisabled = true
      this.reset()
      const claId = row.claId || this.ids
      listClassInfo({claId:Number(claId)}).then(response => {
        this.form = response.rows[0]
        this.open = true
        this.title = "修改班级管理"
        // 选择教师
        listUser({ campusId:response.rows[0].campusId }).then(res => {
          this.teacherInfoList = res.rows
        })
        //选择课表
        listLessonInfo({ campusId:response.rows[0].campusId }).then(res => {
        this.courseInfoList = res.rows
        })
      })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.claId != null) {
            updateCourseCla(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCourseCla(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row,"===========row===========")
      const claIds = row.claId || this.ids
      console.log(claIds,"===========claIds===========")
      this.$modal.confirm('是否确认删除班级管理编号为"' + claIds + '"的数据项？').then(function() {
        return delCourseCla(claIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/courseCla/export', {
        ...this.queryParams
      }, `courseCla_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
.transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }

/* 重新设计穿梭框布局 */
::v-deep .el-transfer {
  display: flex !important;
  align-items: flex-start !important;
  justify-content: center !important;
  width: 100% !important;
  gap: 20px !important;
}

/* 调整左右面板 */
::v-deep .el-transfer-panel {
  width: 280px !important;
  height: 550px !important;
  flex-shrink: 0 !important;
}

::v-deep .el-transfer-panel__body {
  height: 470px !important;
}

::v-deep .el-transfer-panel__list {
  height: 430px !important;
}

::v-deep .el-transfer-panel__header {
  height: 40px !important;
}

::v-deep .el-transfer-panel__filter {
  margin: 15px;
}

/* 重新设计中间按钮区域 - 水平排列 */
::v-deep .el-transfer__buttons {
  display: flex !important;
  flex-direction: row !important;
  align-items: center !important;
  justify-content: center !important;
  align-self: center !important;
  margin: 0 !important;
  gap: 10px !important;
  min-width: 140px !important;
  flex-shrink: 0 !important;
}

::v-deep .el-transfer__button {
  margin: 0 !important;
  min-width: 60px !important;
  flex-shrink: 0 !important;
  padding: 8px 12px !important;
}

/* 优化弹框样式 */
::v-deep .el-dialog__body {
  padding: 20px !important;
}
</style>
